<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel :title="$t('功能目录')" style="padding-right:0;">
        <el-tree class="learun-tree" :data="modulesExpandTree" :expand-on-click-node="false" @node-click="handleNodeClick">
                <span class="lr-tree-node" slot-scope="{ node, data }">
                    <i :class="data.icon"></i>
                    {{ $t(node.label) }}
                </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left:0;">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input placeholder="please enter" @keyup.enter.native="hanleSearch" v-model="keyWord" size="mini">
            <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()">
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
          :loading="tableLoading"
          :columns="columns"
          :dataSource="tableData"
          row-key="f_Id"
          :isPage="true"
          :pageTotal="tableTotal"
          :tablePage.sync="tableCurrentPage"

          @loadPageData="turnTablePage"
      >
        <template v-slot:f_CreateDate="scope">
          {{ lr_dateFormat(scope.row.f_CreateDate) }}
        </template>
        <template v-slot:f_PModuleId="scope">
          {{ (modules.find(t => t.f_ModuleId == scope.row.f_PModuleId) || {}).f_FullName || '' }}
        </template>
        <template v-slot:f_EnabledMark="scope">
          <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.f_EnabledMark"
              @change="handleEnableChange(scope.row)"
          >
          </el-switch>
        </template>
        <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick"></l-table-btns>
      </l-table>
    </l-panel>
    <l-fullscreen-dialog
        :title="`${$t('功能设计')}`"
        :headerMidWidth="320"
        :visible.sync="formVisible"

        :isStep="true"
        :steps="['基本配置','页面设计']"
        :stepActive.sync="stepActive"
        :validateSteps="handleValidateSteps"

        @ok="handleSave"
        @closed="handleClosed"
        @opened="handleOpened"
    >
      <my-form ref="form" :stepActive="stepActive"></my-form>
    </l-fullscreen-dialog>
  </l-layout>
</template>

<script>
import {mapGetters} from "vuex"

const api = window.$api.custmerForm.module

import MyForm from './form'

export default {
  inject: ["admin"],
  components: {
    MyForm
  },
  data() {
    return {
      lr_isPage: true,
      // 设计表单
      stepActive: 0,
      formVisible: false,
      formEdit: false,
      formEditRow: null,

      // 左侧树形
      treeLoading: true,
      treeCategory: '',

      // 表格
      columns: [
        {label: '名称', prop: 'f_Name', minWidth: '150'},
        {label: '上级功能', prop: 'f_PModuleId', minWidth: '120'},
        {label: '状态', prop: 'f_EnabledMark', width: '64', align: 'center'},
        {label: '创建人', prop: 'f_CreateUserName', width: '100', align: 'center'},
        {label: '创建时间', prop: 'f_CreateDate', width: '160'}
      ],
      tableLoading: false,
      tableTotal: 0,
      tablePageSize: 50,
      tableCurrentPage: 1,
      tableData: [],
      keyWord: '',
      tableBtns: [
        {prop: 'Edit', label: 'Edit',width:40},
        {prop: 'Delete', label: 'Delete',width:40}
      ]
    }
  },
  mounted() {
    this.init()
  },
  computed: {
    ...mapGetters(["modules", "modulesExpandTree"])
  },
  methods: {
    init() {
      this.loadTablePage(true)
    },
    updateModules() {
      this.$store.dispatch("system/module/getList")
    },
    loadTablePage() {
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: 'F_ModifyDate DESC,F_CreateDate DESC',
        keyWord: this.keyWord,
        f_PModuleId: this.treeCategory
      }
      api.getPage(queryData).then(res => {
        const data = this.$deepClone(res.data.data)
        this.tableData = data.rows
        this.tableTotal = data.records
        this.tableLoading = false
      }).catch(() => {
        this.tableData = []
        this.tableLoading = false
      })
    },
    turnTablePage({rows}) {
      this.tablePageSize = rows
      this.loadTablePage(true)
    },
    handleNodeClick(node) {
      this.treeCategory = node.id
      this.tableCurrentPage = 1
      this.loadTablePage()
    },
    hanleSearch() {
      this.loadTablePage()
    },
    // 表单部分
    handleAdd() {
      this.formEdit = false
      this.showForm()
    },
    handleEdit($index, row) {
      this.formEdit = true
      this.formEditRow = row
      this.showForm()
    },
    handleDelete($index, row) {
      this.$confirm('This operation will permanently delete the data. Do you want to continue?', 'Tips', {
        confirmButtonText: 'confirm',
        cancelButtonText: 'cancel',
        type: 'warning'
      }).then(() => {
        this.tableData.splice($index, 1)
        this.tableTotal--
        api.remove(row.f_Id).then(() => {
          this.$message({
            type: 'success',
            message: 'Delete  success'
          })
          this.updateModules()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Delete has been canceled'
        })
      })
    },
    handleEnableChange(row) {
      api.updateState(row.f_Id, row.f_EnabledMark).then(() => {
        this.$message({
          type: 'success',
          message: '更新成功!'
        })
        this.updateModules()
      })
    },
    handleSave(showLoading, hideLoading) {
      showLoading('saving data...')
      const postData = this.$refs.form.getForm()
      if (this.formEdit) {
        api.update(this.formEditRow.f_Id, postData).then(() => {
          this.loadTablePage()
          this.updateModules()
          this.$message({
            type: 'success',
            message: '更新成功!'
          })
          this.formVisible = false
          hideLoading()
        }).catch(() => {
          hideLoading()
        })
      } else {
        api.add(postData).then(() => {
          this.loadTablePage()
          this.updateModules()
          this.$message({
            type: 'success',
            message: 'save success!'
          });
          this.formVisible = false
          hideLoading()
        }).catch(() => {
          hideLoading()
        })
      }
    },
    showForm() {
      this.formVisible = true
    },

    handleValidateSteps() {
      return this.$refs.form.validateSteps()
    },

    async handleOpened(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading('Loading data...')
        const data = await this.$awaitWraper(api.get(this.formEditRow.f_Id))
        this.$refs.form.setForm(data)
        hideLoading()
      }
    },
    handleClosed() {
      this.$refs.form.resetForm()
    }
  }
}
</script>